<?php
// 本类由系统自动生成，仅供测试用途
class UserAction extends Action {
    public function index(){
    	$this->level = $this->province = $this->bind = $this->status = 0;
    	I('level') && ($condition['level']=I('level')) && ($this->level = I('level')) && ($this->levelname=M('UserLevel')->where("id={$condition['level']}")->getField('level'));
    	I('province') && ($condition['doctorprovince']=I('province')) && ($this->province = I('province'));
    	if(I('bind')==1){
    		$condition['openid']=array('eq','');
    		$condition['name']=array('neq','');
    		$this->bind = I('bind');
    	}elseif(I('bind')==2){
    		$condition['openid']=array('neq','');
    		$condition['name']=array('neq','');
    		$this->bind = I('bind');    		
    	}

    	I('status') && ($condition['status']=I('status')) && ($this->status=I('status'));
		import('ORG.Util.AdminPage');
		$count = M('User')->where($condition)->count();
		$Page = new Page($count,10);
        $Page->setConfig('theme',"<ul class='pagination'><li><a>%totalRow% %header% %nowPage%/%totalPage% 页</a></li><li>%upPage%</li><li>%first%</li><li>%prePage%</li><li>%linkPage%</li><li>%nextPage%</li><li>%end%</li><li>%downPage%</li>".$gopagenu."</ul>");
		$this->page = $Page->show();
        $this->normallist = D('UserListView')->where($condition)->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->currentpage = $Page->firstRow + 1;
        $this->levels = M('UserLevel')->field('id,level')->select();
        $this->provinces=M('Area')->select();
		$this->display();			   
	}

	public function search(){
		if(I('key')){
			$key = I('key');
			$condition['searchtext'] = array('like',"%$key%");
			import('ORG.Util.AdminPage');
			$count = M('User')->where($condition)->count();
			$Page = new Page($count,10);
	        $Page->setConfig('theme',"<ul class='pagination'><li><a>%totalRow% %header% %nowPage%/%totalPage% 页</a></li><li>%upPage%</li><li>%first%</li><li>%prePage%</li><li>%linkPage%</li><li>%nextPage%</li><li>%end%</li><li>%downPage%</li>".$gopagenu."</ul>");
			$this->page = $Page->show();
	        $this->normallist = D('UserListView')->where($condition)->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
			$this->display("index");	
    	}
	}

	public function add(){
		if (IS_POST){
            $data['name']=I('name');
			$data['image']=I('image');
			$data['hospital']=I('hospital');
			$data['department']=I('department');
			$data['position']=I('position');
			$data['socialposition']=I('socialposition');
			$data['mobile']=I('mobile');
			$data['email']=I('email');
			$data['pinyin']=strtoupper(I('pinyin'));
			$data['resume']=I('resume');
			$data['address']=I('address');
			$data['doctorprovince']=I('province');
			$data['doctorcity']=I('city');
			$data['doctordistrict']=I('district');
			$data['sex']=intval(I('sex'));
			$data['status']=intval(I('status'));
			$data['level']=intval(I('level'));
			$data['token']=uuid();
			$add = M('User')->add($data);
			$searchtext = implode(" ", $data);
			$data['searchtext']=$searchtext;
			if($add){
				$this->ajaxReturn(array('status'=>1),"JSON");
			}else{
				$this->ajaxReturn(array('status'=>0),"JSON");
			}
			exit;
		}
		$condition['id']=intval(I('id'));
		$this->doctor = M('User')->where($condition)->find();
		$this->department = M('Department')->select();
		$this->level = M('UserLevel')->field('id,level')->where('id<3')->select();
		$this->page = I('page');
		$this->display();
	}

	public function edit(){
		if (IS_POST){
            $condition['id']=intval(I('id'));
            $data['name']=I('name');
			$data['image']=I('image');
			$data['hospital']=I('hospital');
			$data['department']=I('department');
			$data['position']=I('position');
			$data['socialposition']=I('socialposition');
			$data['mobile']=I('mobile');
			$data['email']=I('email');
			$data['pinyin']=strtoupper(I('pinyin'));
			$data['resume']=I('resume');
			$data['address']=I('address');
			$data['doctorprovince']=I('province');
			$data['doctorcity']=I('city');
			$data['doctordistrict']=I('district');
			$data['sex']=intval(I('sex'));
			$data['status']=intval(I('status'));
			$searchtext = implode(" ", $data);
			$data['searchtext']=$searchtext;
			$save = M('User')->where($condition)->save($data);
			if($save!==false){
				$this->ajaxReturn(array('status'=>1),"JSON");
			}else{
				$this->ajaxReturn(array('status'=>0),"JSON");
			}
			exit;
		}
		$condition['id']=intval(I('id'));
		$this->doctor = M('User')->where($condition)->find();
		$this->department = M('Department')->select();
		$this->level = M('UserLevel')->field('id,level')->select();
		$this->levels = I('levels');
		$this->province = I('province');
		$this->bind = I('bind');
		$this->status = I('status');
		$this->page = I('page');
		$this->display();
	}

	public function stop(){
		$condition['id']=I('id');
		$data['status']=2;
		$save = M('User')->where($condition)->save($data);
		if($save !== false){
			$this->ajaxReturn(array('status'=>1),"JSON");
		}else{
			$this->ajaxReturn(array('status'=>0),"JSON");
		}
	}
	public function play(){
		$condition['id']=I('id');
		$data['status']=1;
		$save = M('User')->where($condition)->save($data);
		if($save !== false){
			$this->ajaxReturn(array('status'=>1),"JSON");
		}else{
			$this->ajaxReturn(array('status'=>0),"JSON");
		}
	}
	public function importuser(){
		if($filename = $this->uploadcsv()){
			$handle = fopen($filename, 'r'); 
			$result = $this->input_csv($handle); //解析csv 
			$len_result = count($result); 
			if($len_result==0){ 
			    $this->ajaxReturn(array('status'=>0,'msg'=>'没有任何数据'),"JSON");exit;
			}
		    for ($i = 1; $i < $len_result; $i++) { //循环获取各字段值 
		        $data['name'] = iconv('gb2312', 'utf-8', $result[$i][0]); //中文转码 
		        $data['sex'] = $result[$i][1]; 
		        $data['hospital'] = iconv('gb2312', 'utf-8', $result[$i][2]); 
		        $data['address'] =  iconv('gb2312', 'utf-8', $result[$i][3]);
		        $data['department'] = iconv('gb2312', 'utf-8', $result[$i][4]);
		        $data['position'] = iconv('gb2312', 'utf-8', $result[$i][5]);
		        $data['socialposition'] = iconv('gb2312', 'utf-8', $result[$i][6]);
		        $data['mobile'] = $result[$i][7];
		        $data['email'] = $result[$i][8];
		        $data['pinyin'] = $result[$i][9];
		        $data['resume'] = iconv('gb2312', 'utf-8', $result[$i][10]);
		        $data['status'] = $result[$i][11];
		        $data['level'] = $result[$i][12];
		        $data['token'] = uuid();
		        $data['image'] = "./Public/static/headimg.jpg";
		        if($mobile = M('User')->where("mobile='{$data['mobile']}' AND mobile<>''")->getField('mobile')){
		        	//验证手机号码是否存在
		        }else{
		        	if($area = $this->getaddress($data['address'])){
		        		$data['doctorprovince']=$area['province'];
		        		$data['doctorcity']=$area['city'];
		        		$data['doctordistrict']=$area['district'];
		        	}else{
		        		$data['doctorprovince']="上海市";
		        		$data['doctorcity']="上海市";
		        		$data['doctordistrict']="虹口区";
		        	}
		        	$add = M('User')->add($data);
		        	if(!$add){
		        		$this->ajaxReturn(array('status'=>0,'msg'=>M('User')->getLastSql()),"JSON");
		        		fclose($handle);
		        		exit;
		        	}
		        	
		        }
		    } 
		    fclose($handle); //关闭指针 
		    $this->ajaxReturn(array('status'=>1),"JSON");
		}else{
			$this->ajaxReturn(array('status'=>0,'msg'=>$filename),"JSON");exit;
		}
	}

	private function uploadcsv(){
		import('ORG.Net.UploadFile');
		$upload = new UploadFile();// 实例化上传类
		//$upload->maxSize  = 3145728 ;// 设置附件上传大小
		$upload->allowExts  = array('csv');// 设置附件上传类型
		$upload->savePath =  './Public/Uploads/csv/';// 设置附件上传目录
		if(!$upload->upload()) {// 上传错误提示错误信息
			return 0;
		}else{// 上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();
			return $upload->savePath.$info[0]['savename'];
		}		
	}

	private function input_csv($handle){
		setlocale(LC_ALL,array('zh_CN.gbk','zh_CN.gb2312','en_US.utf8'));
	    $out = array (); 
	    $n = 0; 
	    while ($data = fgetcsv($handle, 10000)) { 
	        $num = count($data); 
	        for ($i = 0; $i < $num; $i++) { 
	            $out[$n][$i] = $data[$i]; 
	        } 
	        $n++; 
	    } 
	    return $out; 
	}

	private function getaddress($address){
	   	$key="96892776e636a0c84da96fe40f2c5511";
	   	$url="http://api.map.baidu.com/geocoder/v2/?address=".urlencode($address)."&output=json&ak=".$key;
	   	$res = json_decode(file_get_contents($url),1);	
	   	if($res['status']!=0){
			return 0; 		
	   	}
	   	$back['lng'] = $res['result']['location']['lng'];
	   	$back['lat'] = $res['result']['location']['lat'];

	   	$url="http://api.map.baidu.com/geocoder/v2/?location=".$back['lat'].",".$back['lng']."&output=json&&ak=".$key;;
	   	$res = json_decode(file_get_contents($url),1);
	   	if($res['status']!=0){
			return 0; 		
	   	}
	   	$back['province'] = $res['result']['addressComponent']['province'];
	   	$back['city'] = $res['result']['addressComponent']['city'];
	   	$back['district'] = $res['result']['addressComponent']['district'];

	   	return $back;
	}

}